#include <Arduino.h>
#include <BLECharacteristic.h>
#include "lib/ble.h"
#include "lattice.h"
#include "mpu.h"
#include "lib/cache.h"
#include "lib/strSplit.h"

//蓝牙消息回调
class MyCallbacks : public BLECharacteristicCallbacks
{
    void onWrite(BLECharacteristic *pCharacteristic) override
    {
        std::string rxValue = pCharacteristic->getValue(); //接收信息

        if (rxValue.length() > 0){

            char** arr = strSplit(rxValue.c_str(), ',');
            if(rxValue[0] == 's' && rxValue[1] == 'c'){
                //设置颜色
                bool isTemp = std::stoi(arr[4]) == 155; //临时颜色

                if(!isTemp){
                    String c = String(arr[1])+ ","+ String(arr[2])+ ","+ String(arr[3]);
                    setCache("led_color", String(c));
                }
                setColor(std::stoi(arr[1]), std::stoi(arr[2]), std::stoi(arr[3]), isTemp);

            }else if(rxValue[0] == 'p' && rxValue[1] == 'a'){
                //播放指定动画
                setAnimation(std::stoi(arr[1]), 2);
            }else if(rxValue[0] == 'r' && rxValue[1] == 'e'){
                //重启
                ESP.restart();
            }

            Serial.print("收到消息：");
            Serial.println(rxValue.data());

        }
    }
};

void setup() {
    Serial.begin(115200);
    Serial.println("Device Starting...");
    delay(1000);

    Serial.println("Initialization complete!");
    Serial.println("===================================");

    //启用蓝牙和设置回调
    bleInit(new MyCallbacks());

    //初始化LED矩阵
    ledInit();

    //初始化陀螺仪
    mpuInit(16, 17);

}

void loop() {

    bleLoop();

    ledLoop();

    mpuLoop();

}